package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.service.FileUploadService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Override
    public JsonData uploadHead(HttpServletRequest request, MultipartFile file) {
        String realPath = request.getServletContext().getRealPath("/");
        String originalFilename = file.getOriginalFilename();
        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
            String format = dateTimeFormatter.format(now);
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = CommonUtil.getUUID() + suffix;
            String filePath = realPath  + format;
            File file1 = new File(filePath);
            if (!file1.exists()){
                file1.mkdirs();
            }
            File file2 = new File(filePath+File.separator+fileName);
            file.transferTo(file2);
        } catch (IOException e) {
            log.error("上传头像失败{}",e);
            return JsonData.buildResult(BizCodeEnum.UPLOAD_FILE_ERROR);
        }
        return JsonData.buildSuccess("上传头像成功");
    }
}
